const fs = require("fs");
const path = require("path");
const exec = require("child_process").execSync;
const rollup = require("rollup");
let builds = require("./config").getAllBuilds();
/**
 * console.log(builds);
 * [
    {
      input: 'stepbystep-vue2\\src\\platforms\\web\\entry-runtime-with-compiler.js',
      output: {
        file: 'stepbystep-vue2\\dist\\vue.js',
        format: 'umd',
        name: 'Vue'
      }
    },
    {
      input: 'stepbystep-vue2\\src\\platforms\\web\\entry-runtime.js',
      output: {
        file: 'stepbystep-vue2\\dist\\vue.runtime.js',
        format: 'umd',
        name: 'Vue'
      }
    }
  ]
 */
console.log(builds);
build(builds);
function build(builds) {
  let built = 0;
  const total = builds.length;
  const next = () => {
    buildEntry(builds[built]).then(() => {
      built++;
      if (built < total) {
        next();
      }
    });
  };

  next();
}
// 通过rollup，对不同入口进行打包
function buildEntry(config) {
  const output = config.output;
  const { file } = output;
  const isProd = /(min|prod)\.js$/.test(file);
  return rollup
    .rollup(config)
    .then((bundle) => bundle.generate(output))
    .then(({ output: [{ code }] }) => {
      return write(file, code);
      /**
{
  output: [
    {
      exports: [],
      facadeModuleId: 'g:\\web\\vue\\vue2.0\\stepbystep-vue2\\src\\platforms\\web\\entry-runtime.js',
      isDynamicEntry: false,
      isEntry: true,
      isImplicitEntry: false,
      modules: [Object: null prototype],
      name: [Getter],
      type: 'chunk',
      code: '(function (factory) {\n' +
        "\ttypeof define === 'function' && define.amd ? define(factory) :\n" +
        '\tfactory();\n' +
        "})((function () { 'use strict';\n" +
        '\n' +
        '\n' +
        '\n' +
        '}));\n',
      dynamicImports: [],
      fileName: 'vue.runtime.js',
      implicitlyLoadedBefore: [],
      importedBindings: {},
      imports: [],
      map: null,
      referencedFiles: []
    }
  ]
}
*/
    })
    .catch((error) => {
      console.error(error);
    });
}
let initBuild = 0;
// 写入文件，dest：文件地址，code：代码
function write(dest, code) {
  return new Promise((resolve, reject) => {
    function report(extra) {
      console.log(
        blue(path.relative(process.cwd(), dest)) +
          " " +
          getSize(code) +
          (extra || "")
      );
      resolve();
    }
    // 获取路径的父文件夹
    const getDest = path.dirname(dest);
    // 写入文件时，先判断文件的目录是否存在
    const isDest = fs.existsSync(getDest);
    // 如果不存在，则创建目录
    if (!isDest) {
      fs.mkdirSync(getDest);
    }
    // 如果存在，且是第一次编译，先把目录清空再写入内容
    else if (isDest && initBuild === 0) {
      exec(`rimraf ${getDest}`, {
        stdio: "inherit",
      });
      fs.mkdirSync(getDest);
    }
    initBuild++;
    fs.writeFile(dest, code, (err) => {
      if (err) return reject(err);
      report();
    });
  });
}

function getSize(code) {
  return (code.length / 1024).toFixed(2) + "kb";
}

// 控制台特性样式
function blue(str) {
  return "\x1b[1m\x1b[34m" + str + "\x1b[39m\x1b[22m";
}
